package com.fablesoft.projectdatacollect.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.fablesoft.projectdatacollect.bean.Setting;
import com.fablesoft.projectdatacollect.db.DatabaseContext;
import com.fablesoft.projectdatacollect.db.SettingDBHelper;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Log4jUtil;

import java.util.ArrayList;
import java.util.List;

public class SettingDao {
    private final String TAG = "sglei-setting";
    private final String[] ORDER_COLUMNS = new String[]{"id", "server_name", "server_url", "project_name"};
    private DatabaseContext dbContext;
    private SettingDBHelper ordersDBHelper;

    public SettingDao(Context context) {
        this.dbContext = new DatabaseContext(context);
        ordersDBHelper = new SettingDBHelper(dbContext);
    }

    /**
     * 执行自定义SQL语句
     */
    public void execSQL(String sql) {
        SQLiteDatabase db = null;
        try {
            if (sql.contains("insert") || sql.contains("update") || sql.contains("delete")) {
                db = ordersDBHelper.getWritableDatabase();
                db.beginTransaction();
                db.execSQL(sql);
                db.setTransactionSuccessful();
            }
        } catch (Exception e) {
            Log4jUtil.e(e.toString());
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }

    /**
     * 查询数据库中所有数据
     */
    public List<Setting> getAllData() {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(SettingDBHelper.TABLE_NAME, ORDER_COLUMNS, null, null, null, null, null);

            if (cursor.getCount() > 0) {
                List<Setting> orderList = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    orderList.add(parseBean(cursor));
                }
                return orderList;
            }
        } catch (Exception e) {
            Log4jUtil.e(e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return null;
    }

    /**
     * 新增或更新一条数据
     */
    public boolean insertSetting(Setting setting) {
        SQLiteDatabase db = null;

        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues contentValues = new ContentValues();
            contentValues.put(ORDER_COLUMNS[0], setting.getId());
            contentValues.put(ORDER_COLUMNS[1], setting.getServerName());
            contentValues.put(ORDER_COLUMNS[2], setting.getServerUrl());
            contentValues.put(ORDER_COLUMNS[3], setting.getProjectName());
            db.replaceOrThrow(SettingDBHelper.TABLE_NAME, null, contentValues);
            db.setTransactionSuccessful();
            return true;
        } catch (SQLiteConstraintException e) {
            Log4jUtil.e(e.toString());
        } catch (Exception e) {
            Log4jUtil.e(e.toString());
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 删除一条数据  此处删除Id为7的数据
     */
    public boolean deleteOrder() {
        SQLiteDatabase db = null;

        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            // delete from Orders where Id = 7
            db.delete(SettingDBHelper.TABLE_NAME, "Id = ?", new String[]{String.valueOf(7)});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }


    /**
     * 获取当前Url
     */
    public Setting getCurrentInfo() {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(SettingDBHelper.TABLE_NAME,
                    ORDER_COLUMNS,
                    "id = ?",
                    new String[]{String.valueOf(CommonUtils.SETTING_URL_ID)},
                    null, null, null);

            if (cursor.getCount() > 0) {
                List<Setting> list = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    Setting setting = parseBean(cursor);
                    list.add(setting);
                }
                if (list == null || list.size() <= 0) {
                    return null;
                }
                return list.get(0);
            }
        } catch (Exception e) {
            Log4jUtil.e(e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return null;
    }

    private Setting parseBean(Cursor cursor) {
        Setting setting = new Setting(cursor.getInt(cursor.getColumnIndex(ORDER_COLUMNS[0])),
                cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[1])),
                cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[2])),
                cursor.getString(cursor.getColumnIndex(ORDER_COLUMNS[3])));
        return setting;
    }
}
